#include "lisctl.h"
#include "myserial.h"
#include <errno.h>
#include <pthread.h>
#include "myposix.h"


int serial_fd = -1;

int voice_init(void)
{
    serial_fd = serialOpen(SERIAL_PORT, SERIAL_BAUD);
    printf("%s|%s|%d:serial_fd = %d\n", __FILE__, __func__, __LINE__, serial_fd);
    return serial_fd;
}

void voice_final(void)
{
    if (-1 != serial_fd)
    {
        close(serial_fd);
        serial_fd = -1;
    }
}

void *voice_get(void *arg)
{
    if (-1 == serial_fd)
    {
        serial_fd = voice_init();
        if (-1 == serial_fd)
        {
            perror("serial open error");
            pthread_exit(0);
        }
    }

    mqd_t mqd = -1;
    posix_pt tmp = (posix_pt)arg;
    if (NULL != tmp)
    {
        mqd = tmp->mqd;
    }
    if (-1 == mqd)
    {
        printf("%s|%s|%d:mqd = %d\n", __FILE__, __func__, __LINE__, mqd);
        pthread_exit(0);
    }
    unsigned char buf[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    int len = 0;
   
    pthread_detach(pthread_self());
    printf("%s thread start\n", __func__);
    while (1)
    {
        if (serialDataAvail(serial_fd))
        {
            len = serialGets(serial_fd, buf);
            printf("%s|%s|%d:len = %d\n", __FILE__, __func__, __LINE__, len);
            if (len > 0)
            {
                if (buf[0] == 0xAA && buf[1] == 0x55 && buf[4] == 0x55 && buf[5] == 0xAA)
                {
                    printf("%s|%s|%d:gets->0x%X,0x%X,0x%X,0x%X,0x%X,0x%X\n", __FILE__, __func__, __LINE__,
                           buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
                    posix_send(mqd, buf, len);
                }
                memset(buf, 0, len);
            }
        }
    }
    pthread_exit(0);
}

void *voice_set(void *arg)
{
  pthread_detach(pthread_self());
  if(-1 == serial_fd)
  {
    perror("serial error");
    pthread_exit(0);
  }
   char *tmp = NULL;
  if(NULL != arg)
  {
      tmp = (char *)arg;
      serialPuts(serial_fd, tmp, 6);
  }
  pthread_exit(0);
}

listen_node voice_stu = {
    .listen_name = "voice",
    .init = voice_init,
    .final = voice_final,
    .get = voice_get,
    .set = voice_set,
    .next = NULL};

listen_pt vo_add(listen_pt lisHead) // 遍历链表，添加节点
{
   return lis_add(lisHead, &voice_stu);
}